import React, { Component } from "react"
import {
    View,
    Image,
    StyleSheet,
    Text,
    ScrollView,
    Keyboard,
    TextInput, TouchableOpacity,
    Linking,
    Alert,
    KeyboardAvoidingView
} from "react-native"
import { observer, inject } from 'mobx-react'
import navigationhelper from 'src/components/navigationhelper'
import {deviceWidth, deviceHeight} from "src/util"
import {checkPhone,isIPhoneX} from "src/util"
import Layer from "src/components/Layer"
import StorageDatas from '../../utils/storageDatas'
import NavigationBar from 'react-native-navbar'


@inject('userAuth')
export default class Regist extends Component {
    constructor(props) {
        super(props)
        this.state = {
            showPhoneVerified: false,
            showInvitePhoneVerified: false,
            smsText: '获取验证码',
            isFetchingSMSCode: false,
            isShowPassword: false,
            isShowRepassword: false
        }
    }
    onBlur = () => {
        this.setState({
            focus: undefined
        })
    }
    onRegist = () => {
        if(!this.phone){
            return Layer.showMsg('手机号不能为空')
        }
        if(!this.smsCode){
            return Layer.showMsg('验证码不能为空')
        }
        if(!this.password){
            return Layer.showMsg('密码不能为空')
        }
        if(!this.repassword){
            return Layer.showMsg('确认密码不能为空')
        }
        if(!this.state.showPhoneVerified){
            return Layer.showMsg('手机号有误')
        }
        if(this.repassword !== this.password){
            return Layer.showMsg('两次密码输入不一致')
        }
        // do regist

        this.props.userAuth.Regist({
            mobile: this.phone,
            validate_code: this.smsCode,
            password: this.password,
            repassword: this.repassword,
            recommend_mobile: this.invitePhone
        }).then(() => {
            Layer.showMsg('注册成功')
            navigationhelper.push('Tab')
            let dict = {'userAccount':this.phone,'passAccount':this.password}
            StorageDatas.saveLocalStorage('userAccount',dict);
        }).catch((error) => {
            if(error.message == 'Network request failed'){
                Alert.alert('网络出错', '请先检查您的网络设置?', [
                {
                    text: '是', onPress: () => {
                        Linking.openURL('app-settings:').catch(err => console.log('error', err))
                    }
                },
                { text: '否', onPress: () => { }},
            ])
        }
        else{
            Layer.showMsg(error.message)
        }
        })
    }

    fetchSmsCode = () => {
        if(this.state.isFetchingSMSCode){
            return
        }
        if(!this.phone){
            return Layer.showMsg('手机号不能为空')
        }
        if(!this.state.showPhoneVerified){
            return Layer.showMsg('手机号有误')
        }

        this.props.userAuth.getSmsCode({
            mobile: this.phone
        }).then(() => {
            Layer.showMsg('验证码已发送')
            var timesRun = 0;
            var interval = setInterval(() =>{
                timesRun += 1;
                if(timesRun === 60){
                    this.setState({
                        isFetchingSMSCode: false,
                        smsText: '获取验证码'

                    })
                    clearInterval(interval)
                    return
                }
                this.setState({
                    isFetchingSMSCode: true,
                    smsText: (60 - timesRun)
                })
            }, 1000)
        }).catch(function (error) {
            if(error.message == 'Network request failed'){
                Alert.alert('网络出错', '请先检查您的网络设置?', [
                {
                    text: '是', onPress: () => {
                        Linking.openURL('app-settings:').catch(err => console.log('error', err))
                    }
                },
                { text: '否', onPress: () => { }},
            ])
        }
         else{
            Layer.showMsg(error.message)
          }
        })
    }
    onChangeText = (text, type) => {
        switch (type) {
            case 'phone': {
                this.phone = text
                this.setState({
                    showPhoneVerified: checkPhone(text)
                })
            }
            case 'invitePhone': {
                this.invitePhone = text
                this.setState({
                    showInvitePhoneVerified: checkPhone(text)
                })
            }
            default: {
                this[type] = text
            }
        }
    }

    render() {
        return (
            <KeyboardAvoidingView>
                 <NavigationBar style={{height: isIPhoneX() ? 64: 44}}
                               tintColor={'#fff'}
                               leftButton={
                                   <TouchableOpacity
                                       underlayColor="transparent"
                                       style={{marginLeft:20,marginTop:10,justifyContent:'center', alignItems: 'center'}} onPress={()=>{navigationhelper.goBack()}}>
                                       <View style={styles.leftButton}>
                                           <Image source={require('src/assets/login/backBlack.png')}/>
                                       </View>
                                   </TouchableOpacity>
                 }/>
                {/* <Image source={require('src/assets/login/dingbubeijing.png')}
                       style={{position: 'absolute', top: 0, width: deviceWidth, height: deviceWidth * 379 / 375}}/> */}
                <ScrollView contentContainerStyle={{backgroundColor:'#fff',paddingTop: 20, paddingBottom: 20}}>
                    <View style={styles.container}>
                        <Text style={styles.regist}>注册</Text>
                        <Text style={styles.phone}>手机号</Text>
                        <View style={styles.icon}>
                            <TextInput
                                style={styles.input}
                                placeholder="请输入手机号"
                                onFocus={() => {
                                    this.setState({
                                        focus: 'phoneInput'
                                    })
                                }}
                                onBlur={this.onBlur}
                                onChangeText={(text) => {
                                    this.onChangeText(text, 'phone')
                                }}/>
                            {this.state.showPhoneVerified && <Image source={require('src/assets/login/gou.png')}/>}
                        </View>
                        <RenderLine type="phoneInput" state={this.state}/>
                        <Text style={styles.smsCode}>验证码</Text>
                        <View style={styles.icon}>
                            <TextInput
                                style={styles.input}
                                placeholder="请输入验证码"
                                onFocus={() => {
                                    this.setState({
                                        focus: 'smsCodeInput'
                                    })
                                }}
                                onBlur={this.onBlur}
                                onChangeText={(text) => {
                                    this.onChangeText(text, 'smsCode')
                                }}/>
                            <TouchableOpacity
                                style={[styles.codeBack, {backgroundColor: this.state.isFetchingSMSCode ? 'darkgrey' : '#EF3C3C'}]}
                                onPress={this.fetchSmsCode}>
                                <Text
                                    style={{color:'white', fontSize: 10, fontFamily: 'PingFang SC'}}>
                                    {this.state.smsText}
                                </Text>
                            </TouchableOpacity>
                        </View>
                        <RenderLine type="smsCodeInput" state={this.state}/>
                        <Text style={styles.setPassword}>设置密码</Text>
                        <View style={styles.icon}>
                            <TextInput
                                style={styles.input}
                                placeholder="请输入6-12位字符"
                                placeholderTextColor='#E4E4E4'
                                onFocus={() => {
                                    this.setState({
                                        focus: 'passwordInput'
                                    })
                                }}
                                secureTextEntry={!this.state.isShowPassword}
                                onBlur={this.onBlur}
                                onChangeText={(text) => {
                                    this.onChangeText(text, 'password')
                                }}/>
                            <TouchableOpacity onPress={()=>{
                                this.setState({
                                    isShowPassword: !this.state.isShowPassword
                                })
                            }}>
                            {this.state.isShowPassword ?
                                <Image source={require('src/assets/login/zhenyan.png')}/> :
                                <Image source={require('src/assets/login/biyan.png')}/>}
                            </TouchableOpacity>
                        </View>
                        <RenderLine type="passwordInput" state={this.state}/>
                        <Text style={styles.setPassword}>确认密码</Text>
                        <View style={styles.icon}>
                            <TextInput
                                style={styles.input}
                                placeholder="请输入6-12位字符"
                                placeholderTextColor='#E4E4E4'
                                onFocus={() => {
                                    this.setState({
                                        focus: 'passwordEnsureInput'
                                    })
                                }}
                                secureTextEntry={!this.state.isShowRepassword}
                                onBlur={this.onBlur}
                                onChangeText={(text) => {
                                    this.onChangeText(text, 'repassword')
                                }}/>
                            <TouchableOpacity onPress={()=>{
                                this.setState({
                                    isShowRepassword: !this.state.isShowRepassword
                                })
                            }}>
                            {this.state.isShowRepassword ?
                                <Image source={require('src/assets/login/zhenyan.png')}/> :
                                <Image source={require('src/assets/login/biyan.png')}/>}
                            </TouchableOpacity>
                        </View>
                        <RenderLine type="passwordEnsureInput" state={this.state}/>
                        <Text style={styles.setPassword}>邀请人</Text>
                        <View style={styles.icon}>
                            <TextInput
                                style={styles.input}
                                placeholder="请输入邀请人手机号"
                                placeholderTextColor='#E4E4E4'
                                onFocus={() => {
                                    this.setState({
                                        focus: 'inviteMenInput'
                                    })
                                }}
                                onChangeText={(text) => {
                                    this.onChangeText(text, 'invitePhone')
                                }}
                                onBlur={this.onBlur}/>
                            {this.state.showInvitePhoneVerified && <Image source={require('src/assets/login/gou.png')}/>}
                        </View>
                        <RenderLine type="inviteMenInput" state={this.state}/>
                        <View style={{marginTop:10,display: 'flex', flexDirection: 'row'}}>
                            <View style={{flex: 1,}}/>
                            <Text style={{
                                fontSize: 10,
                                marginTop:10,
                                color: '#8E8E93',
                                fontFamily: 'PingFang SC'
                            }}>新用户注册即已同意</Text>
                            <TouchableOpacity>
                                <Text style={styles.forgetPassword}>《用户注册协议》</Text>
                            </TouchableOpacity>
                        </View>
                        <TouchableOpacity
                            style={styles.registButton}
                            onPress={this.onRegist}>
                            <Text style={styles.registButtonText}>注册</Text>
                        </TouchableOpacity>
                    </View>
                    {/* <View style={{display: 'flex', justifyContent: 'center', alignItems: 'center', marginTop: -20}}> */}
                    

                        {/* <TouchableOpacity
                            onPress={() => {
                                navigationhelper.navigate('Login')
                            }}>
                            <Text style={styles.loginButton}>登录</Text>
                        </TouchableOpacity> */}
                    {/* </View> */}
                </ScrollView>
            </KeyboardAvoidingView>
        )
    }
}

function RenderLine (props) {
    var color = '#E4E4E4'
    if (props.type === props.state.focus) {
        color = '#EF3C3C'
    }
    return (
        <View style={{backgroundColor: color, height: 2, marginTop: 5}} />
    )
}


const styles = StyleSheet.create({
    container: {
        marginLeft: 25,
        height: deviceHeight,
        marginRight: 25,
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: 'white',
        borderRadius: 10,
        paddingTop: 24,
        paddingLeft: 18,
        paddingRight: 18
    },
    regist: {
        fontWeight:'bold',
        fontSize: 26,
        color: '#2E2E2E',
        fontFamily: 'PingFang SC'
    },
    phone: {
        fontSize: 14,
        lineHeight: 17,
        marginTop: 40,
        color: '#8E8E93',
        fontFamily: 'PingFang SC'
    },
    setPassword: {
        fontSize: 14,
        lineHeight: 17,
        marginTop: 20,
        color: '#8E8E93',
        fontFamily: 'PingFang SC'
    },
    smsCode: {
        fontSize: 12,
        lineHeight: 17,
        marginTop: 20,
        color: '#8E8E93',
        fontFamily: 'PingFang SC'
    },
    input: {
        padding:0,
        flex: 1,
        fontSize: 14,
        height:20,
        paddingTop: 0,
        paddingBottom: 0,
    },
    forgetPassword: {
        marginTop:7.5,
        fontSize: 14,
        color: '#EF3C3C',
        fontFamily: 'PingFang SC'
    },
    loginButton: {
        color: '#EF3C3C',
        fontSize: 16,
        fontFamily: 'PingFang SC',
        marginTop: 18
    },
    registButtonText: {
        color: 'white',
        fontSize: 16,
        fontFamily: 'PingFang SC'
    },
    registButton: {
        marginTop:40,
        backgroundColor: '#EF3C3C',
        marginLeft:20,
        marginRight:20,
        height: 50,
        borderRadius: 10,
        justifyContent: 'center',
        alignItems: 'center'
    },
    icon: {
        height: 16,
        marginTop: 18,
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center'
    },
    codeBack: {
        marginTop:-10,
        width: 71,
        height: 25,
        borderRadius: 10,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
    }
})